const axios = require('axios');
const assert = require('assert');
const _ = require('lodash');
const path = require('path');
const apiCfg = require(path.join(__dirname, '../config', 'wxwork.json')).api;

class WxWorkApi {
    constructor() {
        this.baseUrl = apiCfg.base_url;
        this.timeout = apiCfg.timeout ? apiCfg.timeout : 5000;
        this.api = axios.create({
            baseURL: this.baseUrl,
            timeout: this.timeout,
            headers: {'Content-Type': 'application/json'}
        });
    }

    assertOkResponse(response) {
        let { data, status, statusText } = response;
        assert(status == 200, `请求失败[${status}]: ${statusText}`);
        assert(
            data && data.errcode == 0,
            `返回错误：code=${data.errcode} message=${data.errmsg}`
        );
    }

    async getUserIdForLogin(token, code) {
        let response = await this.api.get(apiCfg.funcs.getuserinfo, {
            params: {
                access_token: token,
                code: code,
            },
        });
        this.assertOkResponse(response);
        let { data } = response;
        assert(data.hasOwnProperty('UserId'), '非当前企业用户');
        return data.UserId;
    }

    async getMember(token, userId) {
        let response = await this.api.get(apiCfg.funcs.getMember, {
            params: {
                access_token: token,
                userid: userId,
            },
        });
        this.assertOkResponse(response);
        let member = response.data;
        assert(member.status == 1, '您还没有激活该企业微信账号');

        return _.omit(member, ['errcode', 'errmsg']);
    }
}

module.exports = WxWorkApi;
